<template>
  <!-- 新增页 -->
  <el-card class="box-card el-card-flex addAttachment">
    <div slot="header" class="clearfix">
      <span>
        添加附件
      </span>
    </div>
    <div class="text item">
      <div style="margin-bottom: 50px;overflow: auto;">
        <el-form :model="enclosures" ref="enclosures" :rules="rules" label-width="100px">
          <el-form-item
            label="所属系统:"
            prop="domainId"
            :rules="[
              {
                required: true,
                message: '请选择所属系统',
                trigger: ['blur', 'change']
              }
            ]"
          >
            <el-select v-model="enclosures.domainId" placeholder="请选择所属系统" @change="selectChange">
              <el-option
                v-for="item in this.optionDatas"
                :key="item.domainId"
                :label="item.domainName"
                :value="item.domainId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="大类:" prop="bigCatName">
            <el-tag v-for="(val, index) in bigCatNameTags" :type="nowCheckLargeId === val.attId ? 'success' : ''" :key="index" closable :disable-transitions="false"  @close="handleBigCatNameClose(val)" @click="handleBigCatNameClick(val.attId)">{{val.attFullName}}</el-tag>
            <el-button class="input-new-tag" v-if="largeVisible && largeBtnLoading" size="small">{{enclosures.largeBigCatNameClass}}</el-button>
            <el-input class="input-new-tag" v-else-if="largeVisible" v-model="enclosures.largeBigCatNameClass" ref="largebigCatNameSave" size="small" @keyup.enter.native="handleBigCatInputConfirm" @blur="handleBigCatInputConfirm"></el-input>
            <el-button v-else class="button-new-tag" @click="largeBigCatNameInput">添加大类</el-button>
          </el-form-item>
          <el-form-item label="小类:" prop="smallCatName">
            <el-tag v-for="(val, index) in smallCatNameTags" :type="nowCheckLargeSmallId === val.attId ? 'success' : ''" :key="index" closable :disable-transitions="false"  @close="handleSmallCatNameClose(val)" @click="handleSmallCatNameClick(val.attId)">{{val.attFullName}}</el-tag>
            <el-button class="input-new-tag" v-if="subVisible && largeBtnLoading" size="small">{{enclosures.smallCatName}}</el-button>
            <el-input class="input-new-tag" v-else-if="subVisible" v-model="enclosures.smallCatName" ref="subSmallCatNameSave" size="small" @keyup.enter.native="handleSmallCatNameInputConfirm" @blur="handleSmallCatNameInputConfirm"></el-input>
            <el-button v-else class="button-new-tag" @click="subSmallCatNameInput">添加小类</el-button>
          </el-form-item>
          <el-form-item
            label="业务ID:"
            prop="businessId"
            :rules="[
              {
                required: true,
                message: '请填写业务ID',
                trigger: 'blur'
              }
            ]"
          >
            <el-col :span="10">
              <el-input type="text" v-model="enclosures.businessId" :rows="2" placeholder="请输入内容" >></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="业务编码:" prop="businessCode">
            <el-col :span="18">
                <el-input type="text" v-model="enclosures.businessCode" :rows="2" placeholder="请输入内容" >></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="描述:" prop="businessDesc">
            <el-col :span="18">
                <el-input type="textarea" v-model="enclosures.fileExtension" :rows="2" placeholder="请输入内容" >></el-input>
            </el-col>
          </el-form-item>
          <el-form-item
            label="添加附件:"
            :rules="[
              {
                required: true
              }
            ]"
          >
            <el-col :span="18">
                <el-upload
                  class="upload-demo"
                  action="/api/ccms/attachment/upload"
                  :on-preview="handlePreview"
                  :before-upload="beforeUpload"
                  :before-remove="beforeRemove"
                  multiple
                  :limit="10"
                  :data="{
                    domainId: this.domainId,
                    businessId: this.enclosures.businessId,
                    bigCatId: this.attId,
                    smallCatId: this.nowCheckLargeSmallId,
                    businessCode: this.enclosures.businessCode?this.enclosures.businessCode : '',
                    businessDesc: this.enclosures.fileExtension,
                    sysCode: this.sysCode
                  }"
                  :headers="{
                    Authorization: this.Authorization
                  }"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                  v-model="enclosures.files"
                  ref="upload"
                  :on-change="onChange"
                  :on-success="onSuccess"
                  :on-error="onError"
                  :auto-upload="false"
                >
                <el-button size="small" type="primary">选择文件</el-button>
              </el-upload>
            </el-col>
          </el-form-item>
        </el-form>
      </div >
      <div class="attachFooter">
        <el-button type="primary" @click="handleAattachSave">
          保存
          <i class="el-icon-document-checked el-icon--right"></i>
        </el-button>
        <el-button type="danger" @click="handleAattachClose">
          关闭
          <i class="el-icon-close"></i>
        </el-button>
      </div>
    </div>
  </el-card>
</template>
<script>
import {Dialog, MessageBox, Message,TableColumn, Pagination, Tag,Table, Upload} from 'element-ui'
import { getDomainAuth, findBigCat, findSmallCat } from '@/api/attachment/attachmentQuery/attachmentQuery.js'
import { deleteBigCat, deleteSmallCat, insertBigCat, insertSmallCat } from '@/api/attachment/attachmentQuery/addattAchment.js'
export default {
  components: { //注册插件
    'el-dialog': Dialog, //弹窗
    "el-table-column": TableColumn, //表格列
    "el-pagination": Pagination, //分页
    'el-tag': Tag,
    "el-table": Table, //表格
    "el-upload":Upload, //上传
  },
  data () {
    var dataList = {
      domainId:'',
      largeBigCatNameClass:'',
      subClass:'',
      id:'',
      code:'',
      fileExtension:'',
      files:'',
      upFileIndex: 0, // 上传成功了第几个文件
    }
    return {
      AdvancedQuery:{
        domainId:"",
        largeBigCatNameClass:"",
        subClass:'',
        code:"",
        annexName:""
      },
      nowCheckLargeId: '',
      nowCheckLargeSmallId: '',
      bigCatNameTags: [], // 大类标签tag
      smallCatNameTags: [], // 小类标签tag
      largeVisible: false,
      largeBtnLoading: false,
      subVisible:false,
      AdvancedQuery: JSON.parse(JSON.stringify(dataList)),
      largeBigCatNameClass:[
        {
          value:'费用报销',
          label: '费用报销'
        }
      ],
      smallCatName:[
        {
          value:'销售预算',
          label: '销售预算'
        }
      ],
      fileList: [],
      dataList: JSON.parse(JSON.stringify(dataList)),
      enclosures: JSON.parse(JSON.stringify(dataList)),
      optionDatas: [], // 所属系统下拉数据
      domainId: '', // 大类或者小类里的domainId
      attId: '', // 大类里的attId
      rules:{},
      sysCode: '', // 获取系统sysCode
      Authorization: '', // 获取系统Authorization
    }
  },
  created() {
    // 获取系统下拉框数据
    getDomainAuth({
      domainName: "",
      domainCode: ""
    }).then(res => {
      let domainId
      this.optionDatas = res.data.data
      this.optionDatas.forEach(e => {
        domainId = e.domainId
      })
    })
    this.sysCode = this.getCookie('sysCode')
    this.Authorization = this.getCookie('Authorization')
  },
  computed: {
    // headers() {
    //   return {
    //     "access_token": 'd54e3ef7-6d69-4b4e-afb3-ef539cb80f9b' // 直接从本地获取token就行
    //   }
    // }
  },
  methods: {
    // 获取cookie
    getCookie (cname) {
      var name = cname + "="
      var ca = document.cookie.split(';')
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim()
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length)
      }
      return ""
    },
    // 所属系统改变事件获取到id
    selectChange (domainId) {
      this.bigCatNameTagsData(domainId)
      this.domainId = domainId
      this.smallCatNameTags = []
      // console.log(this.domainId)
    },
    // 获取大类数据
    bigCatNameTagsData (domainId) {
      findBigCat(domainId).then(res => {
        console.log(res)
        this.bigCatNameTags = res.data.data
      })
    },
    //大类删除tag按钮
    handleBigCatNameClose (data) {
      let attId = data.attId
      // this.bigCatNameTags.splice(this.bigCatNameTags.indexOf(largeTag), 1)
      deleteBigCat(attId).then(res => {
				if (res.data.code === 10000) {
          this.bigCatNameTags.splice(this.bigCatNameTags.indexOf(data), 1)
          Message.success('删除成功')
				}
			})
    },
    // 点击大类里的tag获取ID
    handleBigCatNameClick (attId) {
      this.smallCatNameTagsData(attId)
      this.attId = attId
    },
    // 点击小类变背景色
    handleSmallCatNameClick (attId) {
      this.nowCheckLargeSmallId = attId
    },
    // 获取小类数据
    smallCatNameTagsData (bigCatId) {
      this.nowCheckLargeId = bigCatId
      findSmallCat(bigCatId).then(res => {
        // console.log(res)
        this.smallCatNameTags = res.data.data
      })
    },
    //小类删除tag按钮
    handleSmallCatNameClose (data) {
      let attId = data.attId
      // this.smallCatNameTags.splice(this.smallCatNameTags.indexOf(subTag), 1)
      deleteSmallCat(attId).then(res => {
				if (res.data.code === 10000) {
          this.smallCatNameTags.splice(this.smallCatNameTags.indexOf(data), 1)
          Message.success('删除成功')
				}
			})
    },
    // 大类新增tag按钮
    largeBigCatNameInput () {
      if (!this.enclosures.domainId) return Message.warning('请先选择所属系统')
      this.largeVisible = true
      this.$nextTick(_ => {
        this.$refs.largebigCatNameSave.$refs.input.focus()
      })
    },
    //小类新增tag按钮
    subSmallCatNameInput () {
      if (!this.attId) return Message.warning('请先选择大类')
      this.subVisible = true
      this.$nextTick(_ => {
        this.$refs.subSmallCatNameSave.$refs.input.focus()
      })
    },
    // 大类输入确认tag按钮
    handleBigCatInputConfirm() {
      if (this.largeBtnLoading) return
      if (!this.enclosures.largeBigCatNameClass) return this.largeVisible = false
      this.largeBtnLoading = true
      insertBigCat({
        attFullName: this.enclosures.largeBigCatNameClass,
        domainId: this.domainId
      }).then(res => {
        console.log(res)
        if (res.data.code === 10000) {
          this.largeBtnLoading = false
          this.largeVisible = false
          this.bigCatNameTags.push({
            attId: res.data.data,
            attFullName: this.enclosures.largeBigCatNameClass,
          })
          this.enclosures.largeBigCatNameClass = ''
        } else {
          this.largeBtnLoading = false
          this.largeBigCatNameInput()
        }
      }).catch(()=> {
        this.largeBtnLoading = false
        this.largeBigCatNameInput()
      })
    },
    //小类输入确认tag按钮
    handleSmallCatNameInputConfirm() {
      if (this.largeBtnLoading) return
      if (!this.enclosures.smallCatName) return this.subVisible = false
      this.largeBtnLoading = true
      insertSmallCat({
        attFullName: this.enclosures.smallCatName,
        domainId: this.domainId,
        upAttId: this.attId
      }).then(res => {
        console.log(res)
         if (res.data.code === 10000) {
          this.largeBtnLoading = false
          this.subVisible = false
          this.smallCatNameTags.push({
            attId: res.data.data,
            attFullName: this.enclosures.smallCatName,
          })
          this.enclosures.smallCatName = ''
        } else {
          tthis.largeBtnLoading = false
          this.subSmallCatNameInput()
        }
      }).catch(() => {
        this.largeBtnLoading = false
        this.subSmallCatNameInput()
      })
    },
    //删除确认
    beforeRemove(file, fileList) {
      return MessageBox.confirm(`确定移除 ${ file.name }？`)
    },
    // 上传文件之前的钩子
    beforeUpload () {
      this.upFileIndex = 0
      return true
    },
    //点击文件获取文件信息
    handlePreview(file) {
      console.log(file)
    },
    //控制文件个数
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 上传的文件的列表发生变化
    onChange(file, fileList) {
      this.fileList = fileList
    },
    // 保存事件
    handleAattachSave () {
      // if (!this.enclosures.domainId) return Message.warning("请选择系统")
      // if (!this.enclosures.businessId) return Message.warning("请填写业务ID")
      this.$refs.enclosures.validate(valid => {
        if (!valid) return
        if (!this.fileList.length) return Message.warning("请选择需要导入的模板！")
        this.$refs.upload.submit() // 手动触发上传
      })
      // Message.success("上传成功")
    },
    // 文件上传(提交)接口成功
    onSuccess (res, file, fileList) {
      // console.log(res)
      if (res.code === 10000) {
        this.upFileIndex++
        if (this.upFileIndex === fileList.length) {
          Message.success('上传成功')
          this.handleAattachClose()
        }
        console.log('成功', res)
      } else {
        Message.error(res.msg)
      }
    },
    // 文件上传(提交)接口失败
    onError (err) {
      Message.error('上传失败')
      console.log('失败', err)
    },
    // 关闭事件
    handleAattachClose () {
      // this.$router.go(-1) // 返回上一页
       this.$router.push(this.routerMatch({
        name: 'attachmentQuery',
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.addAttachment{
  position: relative;
	.attachFooter {
		position: absolute;
		bottom: 10px;
		right: 20px;
		width: 100%;
		height: 45px;
		line-height: 45px;
		text-align: right;
		background: #ffffff;
    z-index: 999;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: center;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  .el-tag--small{
    cursor: pointer;
    height: 32px;
    line-height: 32px;
  }
}
</style>
<style lang="scss">
.addAttachment{
  .el-tag.el-tag--success {
    background-color: #409EFF;
    border-color: #409EFF;
    color: #fff;
    i {
      color: #fff;
    }
  }
  .el-tag--small {
    margin: 5px 0;
    // &:nth-child(1) {
    //   margin-left: 10px;
    // }
  }
}
</style>